﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization;

namespace ConsumoDeAPI.Model
{
    public class ServiceModel
    {
       private Uri serviceUri;
       public event EventHandler<ResponseEventArg> ServiceResponseReady;
       private string strTextToTranslate;
       private string strLngTo;

   

       public ServiceModel( )
       {

       }
       public ServiceModel(Uri serviceUri) {
           this.serviceUri = serviceUri;
       }

      
        

        public void Request() {

            HttpWebRequest httpR = HttpWebRequest.Create(serviceUri) as HttpWebRequest;
            httpR.BeginGetResponse((AR) => {
                WebResponse resp = httpR.EndGetResponse(AR);
                HttpWebResponse response = (HttpWebResponse)resp;
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();
                // Close the stream object
                streamResponse.Close();
                streamRead.Close();
                // Release the HttpWebResponse
                response.Close();
               ServiceResponseReady(this, new ResponseEventArg(responseString));
            },httpR);
      
        }

        public void RequestBing() 
        {
            //https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27Barquisimeto%27&Market=%27es-ES%27&NewsSortBy=%27Date%27

           // serviceUri = new Uri("https://api.datamarket.azure.com/Bing/Search/v1/Image?Query=%27Barquisimeto%27&ImageFilters=%27Size%3AMedium%27");

            serviceUri = new Uri("https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27Barquisimeto%27&Market=%27es-ES%27&NewsSortBy=%27Date%27");

            var key= "KTiRp7wo3FRCmd/0kngr6H7Mik4lj5YLml9mzMafiTY";
           String authParam = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("ignore" + ":" + key));

//            HttpClient client = new HttpClient();
//client.DefaultRequestHeaders.Authorization = 
//new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authParam);


            HttpWebRequest httpR = HttpWebRequest.Create(serviceUri) as HttpWebRequest;

            httpR.Headers.Add("Authorization: Basic "+ authParam);
            
            httpR.BeginGetResponse((AR) =>
            {
                WebResponse resp = httpR.EndGetResponse(AR);
                HttpWebResponse response = (HttpWebResponse)resp;
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();
                // Close the stream object
                streamResponse.Close();
                streamRead.Close();
                // Release the HttpWebResponse
                response.Close();
                ServiceResponseReady(this, new ResponseEventArg(responseString));
            }, httpR);

        }


        public void RequestBingFoto() 
        {
         
            serviceUri = new Uri("https://api.datamarket.azure.com/Bing/Search/v1/Image?Query=%27Barquisimeto%27&ImageFilters=%27Size%3AMedium%27");

         //   serviceUri = new Uri("https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27Barquisimeto%27&Market=%27es-ES%27&NewsSortBy=%27Date%27");

            var key = "KTiRp7wo3FRCmd/0kngr6H7Mik4lj5YLml9mzMafiTY";
            String authParam = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("ignore" + ":" + key));

            //            HttpClient client = new HttpClient();
            //client.DefaultRequestHeaders.Authorization = 
            //new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", authParam);


            HttpWebRequest httpR = HttpWebRequest.Create(serviceUri) as HttpWebRequest;

            httpR.Headers.Add("Authorization: Basic " + authParam);

            httpR.BeginGetResponse((AR) =>
            {
                WebResponse resp = httpR.EndGetResponse(AR);
                HttpWebResponse response = (HttpWebResponse)resp;
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();
                // Close the stream object
                streamResponse.Close();
                streamRead.Close();
                // Release the HttpWebResponse
                response.Close();
                ServiceResponseReady(this, new ResponseEventArg(responseString));
            }, httpR);

        }





public void traducir() 
{
  // Initialize the strTextToTranslate here, while we're on the UI thread
   strTextToTranslate = "Buenos Días";
  // STEP 1: Create the request for the OAuth service that will
  // get us our access tokens.
  String strTranslatorAccessURI = 
        "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
  System.Net.WebRequest req = System.Net.WebRequest.Create(strTranslatorAccessURI);
  req.Method = "POST";
  req.ContentType = "application/x-www-form-urlencoded";
  // Important to note -- the call back here isn't that the request was processed by the server
  // but just that the request is ready for you to do stuff to it (like writing the details)
  // and then post it to the server.
  IAsyncResult writeRequestStreamCallback = 
    (IAsyncResult)req.BeginGetRequestStream(new AsyncCallback(RequestStreamReady), req);

}
 



private void RequestStreamReady(IAsyncResult ar)
{
   
 // STEP 2: The request stream is ready. Write the request into the POST stream
    string clientID = "VoiceTranslateJl";
    string clientSecret = "1lAvCGdXzRlXZPOveJP+51oLPrQrODXDaM8Qi6WvvZY=";
  String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", System.Web.HttpUtility.UrlEncode(clientID), System.Web.HttpUtility.UrlEncode(clientSecret));

  // note, this isn't a new request -- the original was passed to beginrequeststream, so we're pulling a reference to it back out. It's the same request

  System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)ar.AsyncState;
  // now that we have the working request, write the request details into it
  byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strRequestDetails);
  System.IO.Stream postStream = request.EndGetRequestStream(ar);
  postStream.Write(bytes, 0, bytes.Length);
  postStream.Close();
  // now that the request is good to go, let's post it to the server
  // and get the response. When done, the async callback will call the
  // GetResponseCallback function
  request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
 


    [DataContract]
    public class AdmAccessToken
    {
        [DataMember]
        public string access_token { get; set; }
        [DataMember]
        public string token_type { get; set; }
        [DataMember]
        public string expires_in { get; set; }
        [DataMember]
        public string scope { get; set; }
    }

 


private void GetResponseCallback(IAsyncResult ar)
{
// STEP 3: Process the response callback to get the token
// we'll then use that token to call the translator service
// Pull the request out of the IAsynch result
  HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
// The request now has the response details in it (because we've called back having gotten the response
  HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
// Using JSON we'll pull the response details out, and load it into an AdmAccess token class (defined earlier in this module)
// IMPORTANT (and vague) -- despite the name, in Windows Phone, this is in the System.ServiceModel.Web library,
// and not the System.Runtime.Serialization one -- so you will need to have a reference to System.ServiceModel.Web
  strLngTo = "en";


  try
  {
    System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new 
    System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));
  AdmAccessToken token = 
    (AdmAccessToken)serializer.ReadObject(response.GetResponseStream());
    
    string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(strTextToTranslate) + "&from=es&to=" + strLngTo;
    System.Net.WebRequest translationWebRequest = System.Net.HttpWebRequest.Create(uri);
    // The authorization header needs to be "Bearer" + " " + the access token
    string headerValue = "Bearer " + token.access_token;
    translationWebRequest.Headers["Authorization"] = headerValue;
    // And now we call the service. When the translation is complete, we'll get the callback
    IAsyncResult writeRequestStreamCallback = (IAsyncResult)translationWebRequest.BeginGetResponse(new AsyncCallback(translationReady), translationWebRequest);
    }
    catch (Exception ex)
    {
      // Do nothing
    }
  } 
 



private void translationReady(IAsyncResult ar)
{
  // STEP 4: Process the translation
  // Get the request details
  HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
  // Get the response details
  HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
  // Read the contents of the response into a string
  System.IO.Stream streamResponse = response.GetResponseStream();
  System.IO.StreamReader streamRead = new System.IO.StreamReader(streamResponse);
  string responseString = streamRead.ReadToEnd();
  // Translator returns XML, so load it into an XDocument
  // Note -- you need to add a reference to the System.Linq.XML namespace
  System.Xml.Linq.XDocument xTranslation = 
    System.Xml.Linq.XDocument.Parse(responseString);
  string strTest = xTranslation.Root.FirstNode.ToString();
  // We're not on the UI thread, so use the dispatcher to update the UI
 

}
    }
}
